package com.eascs.o2o.loan.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.service.IOverdueService;
import com.eascs.app.dao.DefaultIdBuilder;
import com.eascs.o2o.loan.until.Configuration;
import com.eascs.site.view.ViewContext;

@Controller
@RequestMapping("/wechat")
public class WeChatController{
	
	/**
	 * 用户授权地址
	 */
	@Value("${wechat.oauth2.url}")
	private String oauth2Url;
	
	/**
	 * 通过code换取网页授权access_token地址
	 */
	@Value("${wechat.oauth2.access.token.url}")
	private String accessTokenUrl;
	
	/**
	 * 取得公众号应用重定向参数URL
	 */
	@Value("${wechat.oauth2.redirect.uri}")
	private String weChatRedirectUrl;
	
	@Reference
	private IOverdueService overdueService;

	@RequestMapping("/oauth2AccessToken")
	public void oauth2AccessToken(HttpServletResponse response,String code,String state) {
		Map<String,String> param=new HashMap<>();
		param.put("appid", getWeChatAppId());
		param.put("secret", "");
		param.put("response_type", getWeChatResponseType());
		param.put("code", code);
		param.put("grant_type", "authorization_code");
		String result=httpRequest(accessTokenUrl,param);
		ViewContext.put("result", result);
	}
	
	@RequestMapping("/base/oauth2")
	public void oauth2Base(HttpServletResponse response) {
		try {
			String state = DefaultIdBuilder.build();
			StringBuffer url=new StringBuffer();
			url.append(oauth2Url);
			url.append("?appid="+getWeChatAppId());
			url.append("&redirect_uri="+URLEncoder.encode(weChatRedirectUrl, "UTF-8"));
			url.append("&response_type="+getWeChatResponseType());
			url.append("&scope="+getWeChatSnsapiBase());
			url.append("&state="+state);
			url.append("#"+getWeChatRedirect());
			response.sendRedirect(url.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 取得公众号应用重定向参数
	 */
	public static String getWeChatRedirect() {
		return Configuration.getInstance().getValue("wechat.redirect");
	}
	
	/**
	 * 取得公众号应用授权作用域(不弹出授权页面)
	 */
	public static String getWeChatSnsapiBase() {
		return Configuration.getInstance().getValue("wechat.scope.snsapi.base");
	}
	
	/**
	 * 取得公众号应用授权作用域(弹出授权页面)
	 */
	public static String getWeChatSnsapiUserinfo() {
		return Configuration.getInstance().getValue("wechat.scope.snsapi.userinfo");
	}
	
	/**
	 * 取得公众号返回类型
	 */
	public static String getWeChatResponseType() {
		return Configuration.getInstance().getValue("wechat.response.type");
	}
	
	/**
	 * 取得公众号的唯一标识
	 */
	public static String getWeChatAppId() {
		return Configuration.getInstance().getValue("wechat.appid");
	}
	
	public static String httpRequest(String url,Map<String,String> param){
		HttpClient httpClient			= new HttpClient();
		PostMethod postMethod			= new PostMethod(url);

		try {
			NameValuePair[] datas		= new NameValuePair[param.keySet().size()];
			int count=0;
			for (String key : param.keySet()) {
				datas[count]=new NameValuePair(key, param.get(key));
				count++;
			}
			postMethod.setRequestBody(datas);

			int statusCode				= httpClient.executeMethod(postMethod);
			byte[] responseByte			= postMethod.getResponseBody();
			String responseBody			= new String(responseByte, "UTF-8");

			return "{'statusCode':"+statusCode+",'responseBody':"+responseBody+"}";
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
		return null;
		
	}
}
